<?php

error_reporting(E_ERROR | E_WARNING | E_PARSE);

require_once("../HT_Client/HT_Client.class.php");
require_once("../functions.inc.php");
require_once("../database.inc.php");
require_once("./hoccleanup.inc.php");

$dbm = connect_db("dbm");
$dbh = connect_db("gene");
$client = new HT_Client();

set_time_limit(3600);

$limitfed = "1";
$limitleague = "1";
$lastupdate = GetLastUpdate();
$limitusers = 250;
$maxactiveusers = 1000;

//update the supporters pseudofed
echo "updating pseudofed\n";
$query = mysql_query("SELECT count(*) num FROM supporters", $dbm) or die (mysql_error());
$row = mysql_fetch_array($query);
mysql_query("REPLACE INTO fed_details VALUES (1,'Supporters of CHPP-ste1n',{$row['num']},'CHPP-ste1n',NULL,NOW())", $dbm) or die (mysql_error());
mysql_query("REPLACE INTO fed_roles VALUES (1,1,'Supporter of CHPP-ste1n',1)", $dbm) or die (mysql_error());
mysql_query("DELETE FROM fed_members WHERE allianceid = 1", $dbm) or die (mysql_error());
mysql_query("INSERT INTO fed_members SELECT userid, 1, 1, since FROM supporters", $dbm) or die (mysql_error());

//remove inactive feds
echo "removing inactive feds\n";
$query = mysql_query("SELECT allianceid FROM fed_log WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(latest) > 21 * 86400", $dbm) or die (mysql_error());
if (mysql_num_rows($query) > 0) while ($row = mysql_fetch_array($query)) {
	echo "deleting fed {$row['allianceid']} due to inactivity\n";
	mysql_query("DELETE FROM fed_roles WHERE allianceid = {$row['allianceid']}", $dbm) or die (mysql_error());
	mysql_query("DELETE FROM fed_members WHERE allianceid = {$row['allianceid']}", $dbm) or die (mysql_error());
	mysql_query("DELETE FROM fed_details WHERE id = {$row['allianceid']}", $dbm) or die (mysql_error());
	mysql_query("DELETE FROM fed_log WHERE allianceid = {$row['allianceid']}", $dbm) or die (mysql_error());
}

if (!$client->Login("weird_ed",'langbein',"Maptrick 2.0 fed import and HoC maintenance")) die ("login failed, aborting.\n");

//remove bots
echo "removing bots\n";
$query = mysql_query(
	"SELECT *
	FROM flags_updated
	WHERE UNIX_TIMESTAMP(lastlogindate) < (UNIX_TIMESTAMP() - 50 * 86400)
	ORDER BY lastlogindate ASC
	LIMIT $limitusers", $dbm
) or die (mysql_error());
echo "selected > 50 day teams\n";

if (mysql_num_rows($query) > 0) while ($row = mysql_fetch_array($query)) {
	$updateresult = updateHoc($row['TeamID'], $client, $dbm);
	if ($updateresult > 0) {
		echo "botChecked {$row['TeamName']} ({$row['TeamID']}) - not bot.\n";
	} else if ($updateresult < 0) {
		mysql_query("DELETE FROM fed_members WHERE userid = {$row['UserID']}", $dbm) or die (mysql_error());
		mysql_query("UPDATE teams_der SET userid = 0 WHERE teamid = {$row['TeamID']}", $dbm) or die (mysql_error());
		echo "botChecked {$row['TeamName']} - is bot, deleted user {$row['UserID']} from all federations, and teams_der is now 0.\n";
	} else {
		echo "error with team {$row['TeamID']}. Trying again next time.\n";
	}
	ob_flush();
	flush();
}

//prepare main filler query
$mainquerytext = "SELECT DISTINCT d.teamid, d.userid
	FROM fed_members m, `teams_der` d
	LEFT JOIN flags_updated u ON d.userid = u.userid
	WHERE u.userid IS NULL
	AND d.userid = m.userid
	ORDER BY membersince ASC
	LIMIT $limitusers";

$allianceid = 0;
$leagueid = 0;
if (isset($_GET['allianceid']) && is_numeric($_GET['allianceid']) && $_GET['allianceid'] > 0) $allianceid = $_GET['allianceid'];
if (isset($_GET['leagueid']) && is_numeric($_GET['leagueid']) && $_GET['leagueid'] > 0) $leagueid = $_GET['leagueid'];

ini_set("memory_limit","100M");

//if there is no work, do something useful, such as filling a country
echo "trying to fill small countries\n";
$query = mysql_query($mainquerytext,$dbm) or die (mysql_error());

if (mysql_num_rows($query) == 0) {
	echo "no fed members pending import, so getting $limitusers coolworthiest, oldest teams from countries with < $maxactiveusers users.\n";
	$mainquerytext = "SELECT d.teamid, d.userid
	FROM teams_der d, leagues_daily l
	LEFT JOIN flags_updated u ON d.userid = u.userid
	WHERE u.userid IS NULL
	AND l.leagueid = d.leagueid
	AND d.userid > 0
	AND d.leagueid = l.leagueid
	AND activeusers < $maxactiveusers
	ORDER BY l.activeusers ASC, d.activationdate ASC
	LIMIT $limitusers";
}

//do we want to do a fed? probably not, but leave the code anyway.
if ($allianceid > 0) {
	$mainquerytext = "SELECT DISTINCT d.teamid, d.userid
        FROM fed_members m, `teams_der` d
        LEFT JOIN flags_updated u ON d.userid = u.userid
        WHERE u.userid IS NULL
	AND d.userid = m.userid
	AND allianceid = $allianceid
	ORDER BY membersince ASC";
}

//do we want to do a league? most probably yes, after the script runs out of things to do!
if ($leagueid > 0) {
	$mainquerytext = "SELECT DISTINCT d.teamid, d.userid
        FROM `teams_der` d
        LEFT JOIN flags_updated u ON d.userid = u.userid
        WHERE u.userid IS NULL
        AND d.userid > 0
        AND d.leagueid = $leagueid
        ORDER BY d.activationdate ASC";
}

if (isset($_GET['debug'])) {
	$mainquerytext = "SELECT u.teamid, u.userid
	FROM flags_updated u
	LEFT JOIN `flags_v2` v ON u.userid = v.userid
	WHERE v.userid IS NULL
	ORDER BY fetcheddate ASC
	LIMIT $limitusers";
}

$query = mysql_query($mainquerytext,$dbm) or die (mysql_error());

echo "done choosing mainquery\n";
if (mysql_num_rows($query) > 0) while ($row = mysql_fetch_array($query)) {
	$updateresult = updateHoc($row['teamid'], $client, $dbm);
        if ($updateresult > 0) {
                echo "inserted previously unimported team {$row['teamid']} (userid: $updateresult)\n";
		ob_flush();
		flush();
        } else if ($updateresult < 0) {
                mysql_query("DELETE FROM fed_members WHERE userid = {$row['userid']}", $dbm) or die (mysql_error());
                mysql_query("UPDATE teams_der SET userid = 0 WHERE teamid = {$row['teamid']}", $dbm) or die (mysql_error());
                echo "since {$row['teamid']} is a bot, deleted user {$row['userid']} from all federations, and teams_der is now 0.\n";
		ob_flush();
		flush();
        } else {
		echo "error with team {$row['teamid']}. Trying again next time.\n";
	}
}
echo "done executing mainquery\n";

if (!$client->Logout()) echo "Logout failed!";

?>
